<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Sales\Entity\OrderGoods;
use Sales\Entity\OrderGoodsReturn;
use Sales\Repository\QuerySearch\OrderGoodsReturnSearch;

class OrderGoodsReturnRepository extends EntityRepository
{
    /**
     * 后台售后申请列表（退换货）
     * @param array $search
     * @return \Doctrine\ORM\Query
     */
    public function findOrderReturnList($search = [])
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('r', 'g.goodsName', 'g.goodsImage', 'g.inSpecGoodsStr')
            ->from(OrderGoodsReturn::class, 'r')
            ->innerJoin(OrderGoods::class, 'g', Join::WITH, 'r.orderGoodsId = g.orderGoodsId')
            ->orderBy('r.addTime', 'DESC');

        $query = OrderGoodsReturnSearch::querySearchData($search, $query);

        return $query->getQuery();
    }

    /**
     * 退换货统计
     * @param string $startTime
     * @param string $endTime
     * @return int|mixed|string
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findOrderReturnCount($startTime = '', $endTime = '')
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('COUNT(r.returnId)')->from(OrderGoodsReturn::class, 'r');
        if (!empty($startTime)) $query->andWhere($query->expr()->gte('r.addTime', ':startTime'))->setParameter('startTime', $startTime);
        if (!empty($endTime))   $query->andWhere($query->expr()->lte('r.addTime', ':endTime'))->setParameter('endTime', $endTime);

        return $query->getQuery()->getSingleScalarResult();
    }
    /*=======================================下面为前台使用=======================================*/
    /**
     * 前台客户的退换货信息
     * @param $userId
     * @return \Doctrine\ORM\Query
     */
    public function shopFindOrderReturnList($userId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('r', 'g.goodsName', 'g.goodsImage', 'g.inSpecGoodsStr')
            ->from(OrderGoodsReturn::class, 'r')
            ->innerJoin(OrderGoods::class, 'g', Join::WITH, 'r.orderGoodsId = g.orderGoodsId')
            ->where('r.userId = :userId')->setParameter('userId', $userId)
            ->orderBy('r.addTime', 'DESC');

        return $query->getQuery();
    }
}